package com.example.imoocmusicdemo.helps;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import java.io.IOException;

public class MediaPlayHelp {

    private static MediaPlayHelp instance;

    private Context mContext;
    private MediaPlayer mMediaPlayer;
    private String mPath;
    private OnMediaPlayerHelpListener OnMediaPlayerHelpListener;


    public static MediaPlayHelp getInstance(Context context) {

        if (instance == null) {
            synchronized (MediaPlayHelp.class) {
                if (instance == null) {
                    instance = new MediaPlayHelp(context);
                }
            }
        }

        return instance;

    }

    private MediaPlayHelp (Context context) {

        mContext = context;
        mMediaPlayer = new MediaPlayer();

    }


//        1、setPath：当前需要播放的音乐
    public void setPath (String path) {

//        1、音乐正在播放，重置音乐播放状态
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.reset();
        }


//        2、设置播放音乐路径
        try {
            mMediaPlayer.setDataSource(mContext, Uri.parse(path));
        }catch (IOException e) {
            e.printStackTrace();
        }

//        3、准备播放
        mMediaPlayer.prepareAsync();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (OnMediaPlayerHelpListener != null) {
                    OnMediaPlayerHelpListener.onPrepared(mp);
                }
            }
        });

    }

//    返回正在播放的音乐路径
    public String getPath () {
        return mPath;
    }

    //        2、start：播放音乐
    public void start(){
        if (mMediaPlayer.isPlaying()) return;
        mMediaPlayer.start();
    }

    //        3、pause：暂停音乐
    public void pause() {
        mMediaPlayer.pause();
    }

    public void setOnMediaPlayerHelpListener(MediaPlayHelp.OnMediaPlayerHelpListener onMediaPlayerHelpListener) {
        OnMediaPlayerHelpListener = onMediaPlayerHelpListener;
    }

    public interface OnMediaPlayerHelpListener {
        void onPrepared(MediaPlayer mp);
    }

}
